
'use strict';

const BaseService = require("./base");
const AuthException = require('../exception/auth');
const NotFoundException = require('../exception/not-found');



class ArticleService extends BaseService{
    // 获取文章列表
    async articleList(body){
        /*
        //筛选项：
        作者userId
        时间类型timeType（1-创建时间，2-审核时间）
        开始时间startTime 结束时间endTime 
        排序order（timeAsc-根据创建时间升序，timeDesc-根据创建时间降序，likeAsc-根据点赞数升序，likeDesc-根据点赞数降序，viewAsc-浏览量升序，viewDesc-浏览量降序）
        关键词类型searchType（1-标题） 
        关键词searchWord 
        当前页currentPage
        每页条数pageSize 
        状态 status
        */
       const params = this.app._.cloneDeep(body);
       if(params.all && !params.searchWord){
        const row = await this.app.model.Article.findAll({
            attributes:{exclude:['delete_time']},
            where:{status:2}
        })
        return row
       }else if(params.allType){
        const row = await this.app.model.Article.findAll({
            attributes:{exclude:['delete_time']},
        })
        return row
       }else if(params.all && params.searchWord!=''){
        const {Op} = this.app.Sequelize
        const row = await this.app.model.Article.findAll({
            attributes:{exclude:['delete_time']},
            where:{
                status:2,
                title:{[Op.like]:`%${params.searchWord}%`}
            }
        })
        return row
       }else if(params.allType && params.user_id){
        const row = await this.app.model.Article.findAll({
            attributes:{exclude:['delete_time']},
            where:{authorId:user_id}
        })
        return row
       }else{
        const {count,rows} = await this.app.model.Article.findAndCountAll({
            distinct:true,
            where:this.queryWhere(params),
            attributes:{exclude:['delete_time']}, 
            ...this.orderOption(params.order),
            ...this.pageParam(params)
        });
        return this.paginate(count, rows,params);
       }
        
    }
    // 排序配置
    orderOption(orderType){
        // 默认时间降序
        //排序order（timeAsc-根据创建时间升序，timeDesc-根据创建时间降序，likeAsc-根据点赞数升序，likeDesc-根据点赞数降序，viewAsc-浏览量升序，viewDesc-浏览量降序）
        const option = {
            'timeAsc':['create_time','ASC'],
            'timeDesc':['create_time','DESC'],
            'likeAsc':['like_count','ASC'],
            'likeDesc':['like_count','DESC'],
            'viewAsc':['view_count','ASC'],
            'viewDesc':['view_count','DESC']
        }
        if(!orderType){
            return {order:[option['timeDesc']]}
        }else{
            return {order:[option[orderType]]}
        }
    }
    // 筛选项
    queryWhere(params){
        const {Op} = this.app.Sequelize
        const { userId,timeType,sumTime,status, searchType,searchWord} = params
        const startTime = sumTime[0]
        const endTime = sumTime[1]
        const where = {}
        if(searchType === 1 && searchWord!==''){
            where[Op.and] = {title:{[Op.like]:`%${searchWord}%`}}
        }
        if(timeType === 1 && startTime!=='' && endTime!==''){
            where[Op.and] = { create_time:{[Op.between]:[startTime,endTime]} }
        }else if(timeType === 2 && startTime!=='' && endTime!==''){
            where[Op.and] = { audit_time:{[Op.between]:[startTime,endTime]} }
        }
        if(userId){
            where.authorId = userId
        }
        if(!isNaN(status) && [0,1,2,3].includes(status)){
            where.status = status
        }
        return where
    }

    // 创建文章或草稿
    async createArticle(body){
        const params = this.app._.cloneDeep(body)
        // status 文章状态 0-草稿 1-未审核 2-审核通过 3-不通过
        if(![0,1,2,3].includes(params.status)){
            throw new AuthException('状态参数错误', 20000);
        }
        // const tagsIds = this.getTagsList.map(item=>item.id)
        // const postTags = params.tags.split(',')
        // for (let i = 0; i < postTags.length; i++) {
        //     if(tagsIds.find(data=>(data == postTags[i])) === undefined){
        //         // 提示标签不存在
        //         return
        //     }
        // }
        if(params.status == 0){
            params.draft_time = new Date() //草稿时间
        }else if(params.status == 1){
            params.create_time = new Date() //创建时间

        }
        params.create_time = new Date()
        params.audit_time = null
        params.view_count = 0
        params.like_count = 0
        await this.app.model.Article.create(params)
    }
    //删除文章 (批量)
    async deleteArticle(ids){
        const { Op } = this.app.Sequelize;
        await this.app.model.Article.destroy({
          where:{
            id:{
              [Op.in]:ids
            }
          }
        })
    }

    // // 获取标签列表
    // async getTagsList(){
    //     return await this.app.model.Tags.findAll()
    // }
    

    //审核文章（通过） （批量）
    async auditArticle(body){
        // targetStatus 1-通过 2-不通过
        const {ids,targetStatus} = body
        await this.app.model.Article.update({ status:targetStatus,audit_time:new Date() },{
            where:{
                id:ids
            }
        })
        const msgContent = targetStatus === 2 ?'你的文章已过审~':'你的文章未过审！'
        const allArticle =  await this.app.model.Article.findAll({
            attributes:{exclude:['delete_time']}
        })
        // 审核后对应用户生成消息
        ids.forEach(async (item)=>{
            let user_id 
            allArticle.forEach(data=>{
                if(item == data.id){
                    user_id = data.authorId
                }
            })
            const postData = {
                type:4,
                content:msgContent,
                article_id:Number(item),
                user_id
            }
            await this.ctx.service.message.createMsg(postData)
        })
    }

    // 获取所有文章(根据ids)
    async findArticles(articleIds){
        const { Op } = this.app.Sequelize;
        const articles = await this.app.model.Article.findAll({
          where: {
            id: {[Op.in]: articleIds}
          }
        });
        return articles
      }

    // 根据id获取文章
      async findArticleById(id){
        const articles = await this.app.model.Article.findOne({
          where: {id}
        });
        let articlesMsg = {}
       

        if (articles === null) {
            throw new NotFoundException('找不到文章', 20000);
        }else{
            
            const tagIds = articles.tags.split(',')
            const topicIds = articles.topic.split(',')
            const tags= await this.app.model.Tags.findAll({
                where:{id:tagIds}
            })
            const topics= await this.app.model.Topic.findAll({
                where:{id:topicIds}
            })
            const author = await this.app.model.AdminUser.findOne({
                where:{id:Number(articles.authorId)}
            })
            console.log(author);
            const tagsName=tags.map(item=>item.tag_name)
            const topicsName=topics.map(item=>item.topic_name)
            const authorName = author.username
            const authorAvatar = author.avatar
            const gender = author.gender
            articlesMsg = {...articles.dataValues,tagsName,topicsName,authorName,authorAvatar,gender }
            return articlesMsg
        }
      }

    // 编辑草稿(发布)
    async editArticle(body){
      const param = this.app._.cloneDeep(body)
      const {id,status,title,main_img,content,tags} = param
      const articles = await this.app.model.Article.findOne({where: {id}});
      if (articles === null) {
          throw new NotFoundException('找不到文章', 20000);
      }
      if(articles.status !== 0){
          throw new AuthException('请选择草稿进行编辑', 20000);
      }
          
      let tips = ""
      const updateObj={ status, title,main_img,content,tags}
      if(status == 0){
          updateObj.draft_update_time = new Date() //草稿更新时间
          tips = "更新草稿成功"
      }else if(status == 1){
          updateObj.create_time = new Date()  //创建时间
          tips = "发布文章成功"
      }
      
      await this.app.model.Article.update(updateObj,{
          where:{
              id
          }
      })
      return tips
    }

    async getReCommentArticle(body){
      const { Op } = this.app.Sequelize;
      const param = this.app._.cloneDeep(body)
      const { tagIds,curArticleId } = param
      const randomTags =  tagIds.sort((a, b) => { return Math.random() > 0.5 ? -1 : 1; })[0]
      const randomArticle = await this.app.model.Article.findAll({
        where:{ tags:{[Op.like]:`%${randomTags}%`},id:{[Op.not]:curArticleId} }
      })
      return randomArticle
    }
}


module.exports = ArticleService;